package com.liuzh.fitnessplan.fragment

import android.annotation.SuppressLint
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.*
import android.os.Bundle
import android.text.Layout
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.fragment.app.Fragment
import androidx.room.Room
import com.liuzh.fitnessplan.R
import com.liuzh.fitnessplan.activity.PlansFactorActivity
import com.liuzh.fitnessplan.database.Database
import com.liuzh.fitnessplan.database.bean.Sports
import com.liuzh.fitnessplan.database.bean.TimePlans
import com.liuzh.fitnessplan.databinding.FragmentMainBinding
import com.liuzh.fitnessplan.databinding.FragmentManagerBinding
import com.liuzh.fitnessplan.tools.AppDataInfo
import com.liuzh.fitnessplan.tools.RoomDatabaseUtil
import org.json.JSONObject
import java.util.*

class ManagerFragment : Fragment() {
    private lateinit var bind : FragmentManagerBinding
    private val db : Database
        get() {
            return RoomDatabaseUtil.instance.getDatabase(activity!!)
        }
    private lateinit var adapter : ManagerFragmentAdapter
    private lateinit var list : MutableList<TimePlans>
    private val broadcastReceiver = UIBroadcastReceiver()
    private val intentFilter = IntentFilter()
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val mView = LayoutInflater.from(activity).inflate(R.layout.fragment_manager,container,false)
        bind = FragmentManagerBinding.bind(mView)
        init()
        return mView
    }

    private fun init() {
        list = db.timeDao().getInitData(AppDataInfo.instance.getId(activity!!)) as MutableList<TimePlans>
        Log.d("Print List Size", " ${list.size}")
        adapter = ManagerFragmentAdapter(activity!!,list)
        bind.managerList.adapter = adapter
    }

    //时间管理的业务逻辑Adapter中修改

    inner class UIBroadcastReceiver() : BroadcastReceiver(){
        override fun onReceive(context: Context?, intent: Intent?) {
            flashListData()
        }

    }

    class ManagerFragmentAdapter constructor(
        private var context: Context,
        private var list: MutableList<TimePlans>
    ): BaseAdapter(){
        private val TAG = "ManagerFragment";
        private class ViewHolder(view : View){
            val textTitle : TextView = view.findViewById(R.id.item_title)
            val textProject : TextView = view.findViewById(R.id.item_sport_project)
            val textRepeat : TextView = view.findViewById(R.id.item_repeat)
            val textTime : TextView = view.findViewById(R.id.item_time)
            val mSwith : Switch = view.findViewById(R.id.item_switch)
        }

        override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
            val view : View?
            val viewHolder : ViewHolder
            if(convertView == null){
                view = LayoutInflater.from(context).inflate(R.layout.item_manager_fragment,parent,false)
                viewHolder = ViewHolder(view)
                view.tag = viewHolder
            }else{
                view = convertView
                viewHolder = view.tag as ViewHolder
            }
            val timePlans = list[position]
            val jsonObject = JSONObject(timePlans.date)
            viewHolder.textTitle.text = timePlans.title
            viewHolder.textProject.text = "项目：${timePlans.project}"
            viewHolder.textRepeat.text = if(timePlans.repeat == "once"){
                "重复：仅明天"
            }else{
                "重复：每天"
            }
            viewHolder.textTime.text = "时间 ${jsonObject["hour"]}:${jsonObject["minute"]}"
            viewHolder.mSwith.isChecked = timePlans.isOpen
            viewHolder.mSwith.setOnCheckedChangeListener { _, isChecked ->
                Log.d(TAG, "ID = ${timePlans.id} Checked  == $isChecked")
                timePlans.isOpen = isChecked
                RoomDatabaseUtil.instance.getDatabase(context).timeDao().setOpenStatus(isChecked,timePlans.id)
                if(!isChecked){
                    cancelAlarm(timePlans.id)
                }else{
                    addAlar(timePlans.id,jsonObject)
                }
            }
            view?.setOnLongClickListener {
                val popupMenu = PopupMenu(context,view)
                popupMenu.inflate(R.menu.manager_item_menu)
                popupMenu.setOnMenuItemClickListener {
                    when(it.itemId){
                        R.id.menu_del -> {
                            RoomDatabaseUtil.instance.getDatabase(context).timeDao().delOneData(timePlans.id)
                            list.remove(list[position])
                            this.notifyDataSetInvalidated()
                            cancelAlarm(timePlans.id)
                        }
                        R.id.menu_update -> {
                            val intent = Intent(context,PlansFactorActivity::class.java)
                            intent.putExtra("id",timePlans.id)
                            intent.putExtra("isAdd",false)
                            context.startActivity(intent)
                        }
                    }
                    false
                }
                popupMenu.show()
                false
            }
            return view as View
        }

        private fun cancelAlarm(id : Int){
            val intent = Intent("com.liuzh.ALARM_BROADCAST")
            //intent.putExtra("id",id)
            val pendingIntent = PendingIntent.getBroadcast(context,id,intent,
                PendingIntent.FLAG_CANCEL_CURRENT)
            val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
            alarmManager.cancel(pendingIntent)
        }

        private fun addAlar(id : Int,time : JSONObject){
            //计算目标时间
            val calendar = Calendar.getInstance()
            val hour : Int = time.getInt("hour")
            val minute : Int = time.getInt("minute")
            var tagHour : Int = if(calendar[Calendar.HOUR_OF_DAY] > hour){
                24 - (calendar[Calendar.HOUR_OF_DAY] - hour)
            }else{
                hour - calendar[Calendar.HOUR_OF_DAY]
            }
            var tagMinute : Int = if(calendar[Calendar.MINUTE] > minute){
                60 - (calendar[Calendar.MINUTE] - minute)
            }else{
                minute - calendar[Calendar.MINUTE]
            }


            val intent = Intent("com.liuzh.ALARM_BROADCAST")
            intent.putExtra("id",id)
            val pendingIntent = PendingIntent.getBroadcast(context,id,intent,PendingIntent.FLAG_CANCEL_CURRENT)
            val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
            alarmManager.setExact(AlarmManager.RTC_WAKEUP,System.currentTimeMillis()+3600*1000*tagHour+60*1000*tagMinute,pendingIntent)
            Log.d("Alarm Info", " 添加闹钟定时器")
        }

        override fun getItem(position: Int): Any {
            return list[position]
        }

        override fun getItemId(position: Int): Long {
            return position.toLong()
        }

        override fun getCount(): Int {
            return list.size
        }

    }

    private fun flashListData(){
        val mutableList = db.timeDao()
            .getInitData(AppDataInfo.instance.getId(activity!!)) as MutableList<TimePlans>
        Log.d("Print List Size ","${mutableList.size}")
        if( mutableList != list) {
            list.clear()
            list.addAll(mutableList)
            adapter.notifyDataSetChanged()
        }
    }

    override fun onStart() {
        intentFilter.addAction("com.liuzh.UPDATE_UI")
        context?.registerReceiver(broadcastReceiver,intentFilter)
        super.onStart()
    }

    override fun onResume() {
        Log.d("Fragment","onResume")
        flashListData()
        super.onResume()
    }

    override fun onDestroy() {
        context?.unregisterReceiver(broadcastReceiver)
        super.onDestroy()

    }

}